#include "DebugManager.hpp"
#include "engine.hpp"
#include <sstream>

namespace wolf
{
using namespace std;

DebugManager::DebugManager(void)
{
	exitKey = SDLK_ESCAPE;
	showingFPS = true;
	instance = this;
	lastTick = 0;
}

DebugManager::~DebugManager(void)
{
	instance = NULL;
}

DebugManager *DebugManager::instance = NULL;

DebugManager *DebugManager::get(void)
{
	return instance;
}

bool DebugManager::onEvent(Engine &engine, SDL_Event &event)
{
	if (event.type == SDL_KEYDOWN && event.key.keysym.sym == exitKey)
	{
		engine.halt();
		return false;
	}
	return true;
}

bool DebugManager::isShowingFPS(void) const
{
	return showingFPS;
}

void DebugManager::setShowingFPS(bool value)
{
	showingFPS = value;
}

SDLKey DebugManager::getExitKey(void) const
{
	return exitKey;
}

void DebugManager::setExitKey(SDLKey key)
{
	exitKey = key;
}

void DebugManager::onDraw(Engine & engine, SDL_Surface *dst)
{
	if (showingFPS)
	{
		stringstream buf;
		unsigned currTick = SDL_GetTicks();
		unsigned diff = currTick - lastTick;
		unsigned fps = 1000 / (diff ? diff : 1);
		lastTick = currTick;
		buf << fps << " FPS";
		int w, h;
		font.textSize(buf.str(), w, h);
		font.writeText(buf.str(), dst, dst->clip_rect.w - w, dst->clip_rect.h - h, Color(255, 255, 255));
	}
}

}
